import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, SafeAreaView, TextInput, TouchableOpacity, FlatList, Alert } from 'react-native';
import Header from '../../../components/Header';
import { openDatabase } from 'react-native-sqlite-storage';

const db = openDatabase({ name: 'WorkData.db', location: 'default' });

interface WorkData {
    id: number;
    title: string;
    content: string;
    createTime: string;
}

interface Work2Props {
    onNavigateToLogin?: () => void;
    onBackPress?: () => void;
}

const Work2: React.FC<Work2Props> = ({ onNavigateToLogin, onBackPress }) => {
    const [title, setTitle] = useState('');
    const [content, setContent] = useState('');
    const [workList, setWorkList] = useState<WorkData[]>([]);

    // 初始化数据库
    useEffect(() => {
        initDatabase();
        loadData();
    }, []);

    // 创建表
    const initDatabase = () => {
        db.transaction((tx) => {
            tx.executeSql(
                'CREATE TABLE IF NOT EXISTS work_data (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, content TEXT, create_time TEXT)',
                [],
                () => console.log('表创建成功'),
                (error) => console.log('表创建失败:', error)
            );
        });
    };

    // 保存数据
    const saveData = () => {
        if (!title.trim() || !content.trim()) {
            Alert.alert('提示', '请输入标题和内容');
            return;
        }

        const createTime = new Date().toLocaleString();

        db.transaction((tx) => {
            tx.executeSql(
                'INSERT INTO work_data (title, content, create_time) VALUES (?, ?, ?)',
                [title.trim(), content.trim(), createTime],
                () => {
                    setTitle('');
                    setContent('');
                    loadData(); // 重新加载数据
                },
                (tx, error) => {
                    Alert.alert('错误', '数据保存失败: ' + error.message);
                }
            );
        });
    };

    // 读取数据
    const loadData = () => {
        db.transaction((tx) => {
            tx.executeSql(
                'SELECT * FROM work_data ORDER BY id DESC',
                [],
                (tx, results) => {
                    const data: WorkData[] = [];
                    for (let i = 0; i < results.rows.length; i++) {
                        data.push(results.rows.item(i));
                    }
                    setWorkList(data);
                },
                (error) => {
                    console.log('数据读取失败:', error);
                }
            );
        });
    };

    // 删除数据
    const deleteData = (id: number) => {
        Alert.alert(
            '确认删除',
            '确定要删除这条记录吗？',
            [
                { text: '取消', style: 'cancel' },
                {
                    text: '确定',
                    onPress: () => {
                        db.transaction((tx) => {
                            tx.executeSql(
                                'DELETE FROM work_data WHERE id = ?',
                                [id],
                                () => {
                                    loadData();
                                },
                                (tx, error) => {
                                    Alert.alert('错误', '删除失败: ' + error.message);
                                }
                            );
                        });
                    }
                }
            ]
        );
    };

    // 渲染列表项
    const renderItem = ({ item }: { item: WorkData }) => (
        <View style={styles.listItem}>
            <View style={styles.itemHeader}>
                <Text style={styles.itemTitle}>{item.title}</Text>
                <TouchableOpacity
                    style={styles.deleteButton}
                    onPress={() => deleteData(item.id)}
                >
                    <Text style={styles.deleteButtonText}>删除</Text>
                </TouchableOpacity>
            </View>
            <Text style={styles.itemContent}>{item.content}</Text>
            <Text style={styles.itemTime}>{item.createTime}</Text>
        </View>
    );

    return (
        <SafeAreaView style={styles.container}>
            <Header
                title="报工2"
                showBackButton={true}
                onNavigateToLogin={onNavigateToLogin}
                onBackPress={onBackPress}
            />

            {/* 输入区域 */}
            <View style={styles.inputSection}>
                <TextInput
                    style={styles.input}
                    placeholder="请输入标题"
                    value={title}
                    onChangeText={setTitle}
                />
                <TextInput
                    style={[styles.input, styles.contentInput]}
                    placeholder="请输入内容"
                    value={content}
                    onChangeText={setContent}
                    multiline
                    numberOfLines={3}
                />
                <TouchableOpacity style={styles.saveButton} onPress={saveData}>
                    <Text style={styles.saveButtonText}>保存数据</Text>
                </TouchableOpacity>
            </View>

            {/* 数据列表 */}
            <View style={styles.listSection}>
                <Text style={styles.sectionTitle}>数据列表 ({workList.length} 条)</Text>
                <FlatList
                    data={workList}
                    renderItem={renderItem}
                    keyExtractor={(item) => item.id.toString()}
                    style={styles.list}
                    showsVerticalScrollIndicator={false}
                />
            </View>
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    inputSection: {
        backgroundColor: '#fff',
        padding: 15,
        marginBottom: 10,
    },
    input: {
        borderWidth: 1,
        borderColor: '#ddd',
        borderRadius: 8,
        padding: 12,
        fontSize: 16,
        marginBottom: 10,
        backgroundColor: '#fff',
    },
    contentInput: {
        height: 80,
        textAlignVertical: 'top',
    },
    saveButton: {
        backgroundColor: '#0076ff',
        padding: 15,
        borderRadius: 8,
        alignItems: 'center',
    },
    saveButtonText: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'bold',
    },
    listSection: {
        flex: 1,
        padding: 15,
    },
    sectionTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 10,
    },
    list: {
        flex: 1,
    },
    listItem: {
        backgroundColor: '#fff',
        padding: 15,
        marginBottom: 10,
        borderRadius: 8,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 3,
    },
    itemHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: 8,
    },
    itemTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333',
        flex: 1,
    },
    deleteButton: {
        backgroundColor: '#ff4444',
        paddingHorizontal: 12,
        paddingVertical: 6,
        borderRadius: 4,
    },
    deleteButtonText: {
        color: '#fff',
        fontSize: 12,
    },
    itemContent: {
        fontSize: 14,
        color: '#666',
        marginBottom: 8,
        lineHeight: 20,
    },
    itemTime: {
        fontSize: 12,
        color: '#999',
        textAlign: 'right',
    },
});

export default Work2; 